<script setup>
import Search from "./components/searchView.vue"; // 搜索框组件
import AllCityList from "./components/allCityList.vue"; // 所有城市列表组件
import ResultCity from "./components/resultCity.vue"; // 结果城市组件
import getInterface from "@/api"; // 接口
import { ref, computed } from "vue";

const showResult = ref(false), // 是否展示结果组件
  originList = ref(null), // 原始数组
  list = ref(null), // 城市列表
  searchVal = ref(""); // 搜索框的值
const cityName = ref(JSON.parse(localStorage.getItem("cityId") || '{"name":""}').name);

const format = (cities) => {
  return cities
    .reduce((res, city) => {
      const first = city.pinyin[0].toUpperCase(); // 拿到每一项的拼音首字母大写后的结果
      const findType = res.find((v) => v.type === first); // 在结果res中按照type查找
      if (findType) {
        // 如果找到了
        findType.children.push(city); // 在找到的那一项里面childre里面再加一项city
      } else {
        // 如果没有找到
        res.push({
          // 给res数组添加一项行的
          type: first, // 拼音首字母
          children: [city], // 城市
        });
      }
      return res; // 返回结果
    }, [])
    .sort((a, b) => a.type.localeCompare(b.type)); // 进行排序
};

// 获取城市列表
const getCity = async () => {
  const res = await getInterface(
    {
      k: 6037502,
    },
    "city.list"
  );
  // console.log(res.data.data.cities)
  originList.value = res.data.data.cities;
  // console.log(this.originList)
  list.value = format(originList.value);
};
// 重新排列数据

const resultCityList = computed(() => {
  if (!searchVal.value) return [];
  return originList.value.filter(
    (v) => v.name.includes(searchVal.value) || v.pinyin.includes(searchVal.value)
  );
});

getCity(); // 创建之后调用接口拿数据
</script>

<template>
  <div class="app">
    <header>当前城市-{{ cityName }} <i @click="$router.back">&times;</i></header>
    <Search v-model:showResult="showResult" v-model:searchVal="searchVal" />
    <ResultCity v-if="showResult" :resultCityList="resultCityList" />
    <AllCityList v-else :list="list" :originList="originList" />
  </div>
</template>

<style lang="scss" scoped>
.app {
  font-size: 0.16rem;
  overflow: hidden;
  background: #f4f4f4;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;

  header {
    height: 0.44rem;
    border-bottom: 0.01rem solid #f8f8f8;
    background: #fff;
    line-height: 0.44rem;
    position: relative;
    text-align: center;

    i {
      font-size: 0.3rem;
      position: absolute;
      top: -0.03rem;
      left: 0.03rem;
      color: var(--cl-wh);
      font-weight: normal;
    }
  }
}
</style>
